package com.topisv.tms.web.stock.outstorage;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.stock.oustorage.OutstorageBillItem;
import com.topisv.tms.entity.stock.oustorage.OutstoragePickTask;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.outstorage.OutstorageBillItemService;
import com.topisv.tms.service.stock.outstorage.OutstoragePickTaskService;
import com.topisv.tms.service.vo.WorkOrderInfoVo;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.tools.ExcelUtils;

/**
 * 出库拣货任务_control
 * @author ch
 */
@Controller
@RequestMapping(value = "v2/outstoragePickTask")
public class OutstoragePickTaskController {

	private static final Logger logger = LoggerFactory.getLogger(OutstoragePickTaskController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private OutstoragePickTaskService outstoragePickTaskService;
	@Autowired
	private OutstorageBillItemService outstorageBillItemService;
	
    @Autowired
    private WorkTaskService workTaskService;
	/**
	 * 导向拣货任务列表页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toPickTaskListPage")
	public String toPickTaskListPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
		    
		    //查找我的拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", curUser.jobuuid);
		    param_my.put("status", "myTask");
		    List<OutstoragePickTask> myTaskList=this.outstoragePickTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myPickTaskList",myTaskList);
		    
		    //如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//未分配的拣货任务
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			    param_untaked.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param_untaked.put("status", "undo"); 
			    List<OutstoragePickTask> untakedPickTaskList=this.outstoragePickTaskService.loadTaskByParam(param_untaked);
			    model.addAttribute("untakedPickTaskList",untakedPickTaskList);
			}
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				
				String customerCode=customerList.get(0).getCustomerCode();
				model.addAttribute("_customerCode",customerCode);
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//未分配的拣货任务
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", customerCode);
			    param_untaked.put("status", "undo"); 
			    List<OutstoragePickTask> untakedPickTaskList=this.outstoragePickTaskService.loadTaskByParam(param_untaked);
			    model.addAttribute("untakedPickTaskList",untakedPickTaskList);
				
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstoragePickTaskList";
	}
	
	
	/**
	 * 查询拣货任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryPickTaskList")
	public String queryPickTaskList(Model model, ServletRequest request, ServletResponse response) throws Exception {
		try {
		
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查找我的拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", curUser.jobuuid);
		    param_my.put("status", "myTask"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
		    List<OutstoragePickTask> myPickTaskList=this.outstoragePickTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myPickTaskList",myPickTaskList);
			
		    //查询未分配的拣货任务
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) param.get("warehouseCode");
			String customerCode=(String) param.get("customerCode");
			
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("status", "undo"); 
			
			List<OutstoragePickTask> untakedPickTaskList = this.outstoragePickTaskService.loadTaskByParam(param);
			model.addAttribute("untakedPickTaskList", untakedPickTaskList);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_customerCode", customerCode);
			
			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstoragePickTaskList";
	}
	

	/**
	 * 领取拣货任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakePickTask")
	@ResponseBody
	public String ajaxTakePickTask(ServletRequest request,HttpServletResponse response) {
		try {	
			Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			this.outstoragePickTaskService.takeTask(taskId,curUser.jobuuid);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 导向拣货页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toPickTaskPage/{taskId}", method = RequestMethod.GET)
	public String toPickTaskPage(@PathVariable("taskId") Long taskId, Model model) {
		try {

			OutstoragePickTask  task=this.outstoragePickTaskService.loadTaskById(taskId);
		    model.addAttribute("task", task);
		    
		    //查询任务明细
		    List<OutstorageBillItem> itemList=this.outstorageBillItemService.loadByBillCode(task.getBillCode());
		    model.addAttribute("itemList", itemList);
		    
		    return "stock/outstorage/outstoragePickTask";
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	
	/**
	 * 导向打印拣货单页面_多件
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toPrintPickInfo/{taskId}", method = RequestMethod.GET)
	public String toPrintPickInfo_multi(@PathVariable("taskId") Long taskId, Model model) {
		try {
			//任务信息
			OutstoragePickTask  task=this.outstoragePickTaskService.loadTaskById(taskId);
		    
			model.addAttribute("task",task);
			
			//拣货信息
			//查询任务明细
		    List<OutstorageBillItem> itemList=this.outstorageBillItemService.loadByBillCode(task.getBillCode());
		    model.addAttribute("itemList", itemList);
		    
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/pick/printPickInfo";
	}
	
	/**
	 * 导出拣货单_多件
	 */
	@RequestMapping(value = "exportExcel/{taskId}")
	public String exportExcel_multi(@PathVariable("taskId") Long taskId, Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//任务信息
			OutstoragePickTask  task=this.outstoragePickTaskService.loadTaskById(taskId);
			model.addAttribute("task",task);
			
			//拣货信息
			/*List<Map.Entry<String,Integer>> printInfoList=this.workTaskService.loadPrintInfo_multi(taskCode);
		    model.addAttribute("printInfoList",printInfoList);*/
		    
		    Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskId", taskId);
			 List<OutstorageBillItem> taskItemList=this.outstorageBillItemService.loadByBillCode(task.getBillCode());
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			int goodNum=0;
			for (int i = 0; i < taskItemList.size(); i++) {
				try {
				
					OutstorageBillItem info=taskItemList.get(i);
				
				Object[] obj = {
						i+1,
						info.getCustomerCode(),
						info.getWarehouseCode(),
					    info.getStockCode(),
					    info.getBoxCode(),
					    info.getSku(),
					    info.getSkuName(),
					    (Integer)info.getNum(),
					    "",
					    null
				};
				goodNum+=info.getNum();
				list.add(obj);
				
				} catch (Exception e) {
					
					logger.error("error",e);
				}
				
			}
			Object[] obj = {
					null,
					null,
					null,
					null,
					null,
					null,
					null,
					goodNum,
				    "",
				    null
			};
			list.add(obj);
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","库位", "箱位","sku","sku名称", "数量","备注"};
			String filepath = "拣货单_"+task.getTaskCode()+".xls";
			String title_page="拣货单（任务编号："+task.getTaskCode()+"）";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			logger.error("error",e);
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	
	/**
	 * 完成拣货任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCompletePickTask")
	@ResponseBody
	public String ajaxCompletePickTask(ServletRequest request,HttpServletResponse response) {
	    boolean isLockSuccess = false;
	    Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
		try {	
		    isLockSuccess = workTaskService.lock("ajaxCompletePickTask", taskId+"", "-");
            if (!isLockSuccess) {
                return "false";
            }
            
			this.outstoragePickTaskService.completeTask(taskId);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("ajaxCompletePickTask", taskId+"");
            }
        }
	}
	/**
	 * 打印拣货单
	 * @param taskCode
	 * @param response
	 */
	@RequestMapping(value="ajaxPrintPickInfo",method = RequestMethod.POST)
	public void ajaxPrintPickInfo(@RequestParam(value = "billCode") String billCode,
			HttpServletResponse response){
		PrintWriter out=null;
		JSONObject json=null;
		try {
			json=new JSONObject();
			out=response.getWriter();
			//拣货任务项
			List<OutstorageBillItem> itemList=this.outstorageBillItemService.loadByBillCode(billCode);
		    json.put("itemList", itemList);
			json.put("status","1");
			out.print(json.toString());
		} catch (IOException e) {
			json.put("status","0");
			logger.error("error",e);
		}
	}
}
